import { container } from "tsyringe"
import { RunableTask } from "./task"
import { Context } from "./ctx"
import { CURRENT_APP } from "./app"
import { KwaiApp } from "./KwaiApp"
import dayjs, { Dayjs } from "dayjs"
import { $, kwai, updateFloat } from "../utils"
import { httpGetAsync, httpPost } from "../autox/http"
declare const runtime: any;
export class RandomFindRedPacketTask extends RunableTask {
    title: string = `从直播大厅-找红包`
    type: string = `RandomFindRedPacketTask`
    run() {
        // 进入直播间
        const ctx = container.resolve(Context)
        const currentApp = ctx.get(CURRENT_APP)
        if (KwaiApp.is(currentApp)) {
            updateFloat({ toast: `进入直播大厅，开始找红包` })
            this.collectRedPacket()
            return;
        }
        updateFloat({ toast: `正在打开快手应用，进入随机直播间` })
        this.openKsLive()
        // app.launchPackage(KwaiApp.packageName)
        sleep(5000)
    }
    openKsLive(signal: boolean = true) {
        let flag: any = signal ? Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK : Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
        const uri = `kwai://liveaggregatesquare`
        const intent = app.intent({
            action: "android.intent.action.VIEW",
            data: uri,
            flags: flag
        });
        context.startActivity(intent);
    }
    canRun(): boolean {
        return true;
    }
    isRuning: boolean = true;
    stop(): void {
        this.isRuning = false;
    }
    /**
     * 搜集红包信息
     */
    private maxTime: number = 1000 * 20;
    private minMoney: { [key: string]: number } = {
        [`0`]: 50,
        [`1`]: 1,
        [`2`]: 60,
    };
    private roomCount: number = 0;
    private failCount: number = 0;
    private collectRedPacket() {
        log(`正在搜集红包信息`)
        while (this.isRuning) {
            try {
                updateFloat({ toast: `已扫描${this.roomCount + 1}个房间，速率参数：${this.maxTime}`, currentResult: `正在扫描第${this.roomCount + 1}个房间...` })
                const latestActivity = runtime.info.latestActivity;
                if (['zd4.q', 'n27.a', 'u27.a', 'gqc.a', 'com.kuaishou.live.basic.dialog.LiveDialogContainerFragment$b'].includes(latestActivity)) {
                    back();
                    sleep(2000)
                }
                const nowTime = new Date().getTime()
                const node = selector().id("live_red_packet_status_text").visibleToUser(true).findOne(this.maxTime)
                const useTime = new Date().getTime() - nowTime;
                this.maxTime = Math.floor((useTime + this.maxTime) / 2) + 2000;
                if (!node) {
                    this.failCount += 1;
                    this.maxTime += 500 + this.failCount * 500;
                    const latestActivity = runtime.info.latestActivity;
                    const latestPackage = runtime.info.latestPackage;
                    log(`${latestPackage}-${latestActivity}`)
                    if (['zd4.q', 'n27.a', 'u27.a', 'com.kuaishou.live.basic.dialog.LiveDialogContainerFragment$b'].includes(latestActivity)) {
                        back();
                        sleep(2000)
                    } else {
                        // 找弹框
                        const needBackNode = selector().textMatches(/领取并使用|关注并领取|分享|抢红包/).visibleToUser(true).findOne(3000)
                        if (needBackNode) {
                            const text = needBackNode.text()
                            if (text === '分享') {
                                if (needBackNode.id().includes(`live_bottom_bar_item_title_text_view`)) {
                                    back()
                                    sleep(2000)
                                }
                            } else {
                                back()
                                sleep(2000)
                            }
                        }
                        const clickNode = selector().textMatches(/立即关注|直播已结束|以后再说/).visibleToUser(true).findOne(3000)
                        if (clickNode) {
                            const text = clickNode?.text()
                            if (text === `立即关注`) {
                                $.clickButton(clickNode)
                                sleep(2000)
                            }
                            else if (text === '直播已结束') {
                                log(`直播已结束`)
                            }
                            else if (text === '以后再说') {
                                $.clickButton(clickNode)
                                sleep(2000)
                            }
                        }
                    }
                } else {
                    this.failCount = 0;
                    try {
                        const onlineNode = selector().id("live_audience_count_text").visibleToUser(true).findOne()
                        if (!onlineNode) throw new Error(`没有找到在线人数`)
                        const online = parseInt(onlineNode.text())
                        $.clickButton(node)
                        sleep(3000)
                        const redPackets = this.getRedPacketInfo(dayjs(), online)
                        updateFloat({ currentResult: `[${this.roomCount + 1}]获取红包信息成功` })
                        back()
                        const link = this.getShareLink()
                        updateFloat({ currentResult: `[${this.roomCount + 1}]成功获取分享链接` })
                        httpPost('addRedPkg', { redPackets, ...link }).catch(e => { })
                    } catch (e) {
                        updateFloat({ tip: `[${this.roomCount + 1}]${e.message}` })
                        const onlineNode = selector().id("live_audience_count_text").visibleToUser(true).findOnce()
                        if (!onlineNode) {
                            back()
                            sleep(2000)
                        }
                    } finally {
                        sleep(2000)
                    }
                }
            } catch (e) {
                updateFloat({ tip: `[${this.roomCount + 1}]${e.message}` })
            } finally {
                $.swipeUp()
                sleep(3000)
                this.roomCount += 1;
            }
        }
    }
    private getShareLink() {
        const more = selector().id("live_bottom_bar_single_icon_container").visibleToUser(true).findOne()
        $.clickButton(more);
        const share = selector().id("live_bottom_bar_item_title_text_view").text(`分享`).visibleToUser(true).findOne()
        $.clickButton(share);
        const copy = selector().text(`复制链接`).visibleToUser(true).findOne()
        $.clickButton(copy);
        sleep(1000)
        const link = getClip()
        if (link) {
            const res = link.match(/(http.*?) (.*?)的直播/)
            if (res && res.length > 0) {
                const link = res[1]
                const name = res[2]
                const shareLink = this.getRealLink(link)
                return {
                    name,
                    originLink: link,
                    ...shareLink,
                }
            }
        }
        return {}
    }

    private getRealLink(link: string) {
        const response = httpGetAsync(link)
        const url = response?.url.toString() as string;
        const [path, query] = url.split(`?`)
        const res = path.match(/fw\/live\/(.*)/)
        if (res && res.length > 0) {
            const [, ksid] = res;
            const params: any = {}
            query.split('&').map(key => {
                const [name, value] = key.split('=');
                params[name] = value;
            });
            return { ...params, ksid, originUrl: link };
        }
        return {}
    }

    private getRedPacketInfo(getTime: Dayjs, online: number) {
        let redPackets: any[] = kwai.getRedPacketInfo()
        if (!Array.isArray(redPackets)) {
            throw new Error(`[${this.roomCount}]暂无红包:kwai.getRedPacketInfo.redPackets数据异常`)
        }
        if (!redPackets) {
            throw new Error(`[${this.roomCount}]暂无红包:kwai.getRedPacketInfo.redPackets为空`)
        }
        if (redPackets.length <= 0) {
            throw new Error(`[${this.roomCount}]暂无红包:kwai.getRedPacketInfo.redPackets长度为空`)
        }
        /**
         * 有红包 区分红包类型及金额
         */
        const redPacketsList = redPackets.map(it => {
            const text = it.__text as string;
            if (!text) return;
            const isDefaultRedPacket = text.match(/主播的快币红包(.*?)快币(.*?)开奖时需要留在直播间/);
            if (isDefaultRedPacket && isDefaultRedPacket.length > 0) {
                const [, count, btn] = isDefaultRedPacket;
                const moneyCount = parseInt(count.trim())
                if (!this.minMoney[`0`]) return;
                if (moneyCount < this.minMoney[`0`]) {
                    return;
                }
                return { count: moneyCount, type: 0, btn: btn.trim(), online, text };
            }
            const isFansRedPacket = text.match(/主播的粉丝团红包(.*?)x(.*?)快币(.*?)加入主播粉丝团，即可参与抢红包/);
            if (isFansRedPacket && isFansRedPacket.length > 0) {
                const [, count, total, btn] = isFansRedPacket;
                const moneyCount = parseInt(count.trim())
                if (!this.minMoney[`1`]) return;
                if (moneyCount < this.minMoney[`1`]) {
                    return;
                }
                return { count: moneyCount, type: 1, total: parseInt(total.trim()), btn: btn.trim(), online, text };
            }
            const isCommentRedPacket = text.match(/主播的口令红包(.*?)快币 口令：(.*?)\s(.*?)\s在评论区发送口令，即可参与抢红包/)
            if (isCommentRedPacket && isCommentRedPacket.length > 0) {
                const [, count, comment, btn] = isCommentRedPacket;
                const moneyCount = parseInt(count.trim())
                if (!this.minMoney[`2`]) return;
                if (moneyCount < this.minMoney[`2`]) {
                    return;
                }
                return { count: moneyCount, comment, type: 2, btn: btn.trim(), online, text };
            }
            const isTimeRedPacket = text.match(/锦衣卫（5...的快币红包(.*?)快币(.*?)关注TA，更容易抢到红包/)
            if (isTimeRedPacket && isTimeRedPacket.length > 0) {
                const [, count, time] = isTimeRedPacket;
                const openTime = (getTime as Dayjs).add(parseInt(time.trim()), 'second')
                const moneyCount = parseInt(count.trim())
                if (!this.minMoney[`3`]) return;
                if (moneyCount < this.minMoney[`3`]) {
                    return;
                }
                return { count: moneyCount, time, type: 3, openTime, online, text };
            }
            const isShareRedPacket = text.match(/主播的分享红包(.*?)x(.*?)快币(.*?)分享直播间即可参与抢红包/)
            if (isShareRedPacket && isShareRedPacket.length > 0) {
                const [, count, total, btn] = isShareRedPacket;
                const moneyCount = parseInt(count.trim())
                if (!this.minMoney[`4`]) return;
                if (moneyCount < this.minMoney[`4`]) {
                    return;
                }
                return { count: moneyCount, total: parseInt(total.trim()), online, type: 4, btn: btn.trim(), text };
            }
            const isTaskRedPacket = text.match(/完成任务可瓜分红包.*?\s(.*?)快币\s(.*?)\s(.*?)\s/)
            if (isTaskRedPacket && isTaskRedPacket.length > 0) {
                const [, count, type, btn] = isTaskRedPacket;
                const moneyCount = parseInt(count.trim())
                if (!this.minMoney[`5`]) return;
                if (moneyCount < this.minMoney[`5`]) {
                    return;
                }
                return { count: moneyCount, type: 5, btn: btn.trim(), online, text };
            }
            const isRenqiRedPacket = text.match(/人气票人数达成 开红包x(.*?)\sx(.*?)\s/)
            if (isRenqiRedPacket && isRenqiRedPacket.length > 0) {
                const [, count, total] = isRenqiRedPacket;
                const moneyCount = parseInt(count.trim())
                if (!this.minMoney[`6`]) return;
                if (moneyCount < this.minMoney[`6`]) {
                    return;
                }
                return { count: moneyCount, type: 6, online, total: parseInt(total.trim()), text };
            }
            log(text)
            return;
        }).filter(it => !!it);
        if (redPacketsList && redPacketsList.length > 0) return redPacketsList;
        throw new Error(`[${this.roomCount}]暂无红包：不符合条件`)
    }
}